namespace IAM.Interface.Common.Context
{
    using IAM.Interface.Common;
    using IAM.Interface.Common.Abnormity;
    using IAM.Interface.Common.Encrypt;
    using IAM.Interface.Common.XMLResolution;
    using IAM.Interface.DAL.Response;
    using IAM.Interface.Model;
    using IAM.Interface.Model.ENUM;
    using IAM.Interface.Model.Interface;
    using System;
    using System.Configuration;
    using System.Web;
    using System.Xml;

    public class ResponseContextControl
    {
        private ResponseContextModel _contextmodel;
        private IAM.Interface.Common.Abnormity.ResponseException _re;
        private IAM.Interface.Common.XMLResolution.Request _request;
        private string _xml;

        public ResponseContextControl()
        {
            this._contextmodel = null;
            this._xml = "";
            this._request = null;
            this._re = null;
        }

        public ResponseContextControl(ResponseContextModel contextmodel)
        {
            this._contextmodel = null;
            this._xml = "";
            this._request = null;
            this._re = null;
            this._contextmodel = contextmodel;
        }

        public string ContextControl()
        {
            object obj2 = null;
            try
            {
                obj2 = this.Incept();
            }
            catch (IAM.Interface.Common.Abnormity.ResponseException exception)
            {
                this.ResponseException = exception;
                return this.Send(new NullityObj(), new IAM.Interface.Common.XMLResolution.Request(), this.ResponseException);
            }
            catch (Exception exception2)
            {
                this.ResponseException = new IAM.Interface.Common.Abnormity.ResponseException();
                this.ResponseException.SetStateMessage(500, exception2.Message);
                return this.Send(new NullityObj(), new IAM.Interface.Common.XMLResolution.Request(), this.ResponseException);
            }
            object obj3 = this.TransferBLL(obj2, this.Request);
            return this.Send((IConvertXml) obj3, this.Request, this.ResponseException);
        }

        public static string GetConfigKey()
        {
            string cryptoText = ConfigurationSettings.AppSettings["IAM_Key"];
            EncryptDecrypt decrypt = new EncryptDecrypt();
            decrypt.Key = decrypt.GenerateKey();
            return decrypt.Decrypt(cryptoText);
        }

        private object Incept()
        {
            EncryptDecrypt decrypt = new EncryptDecrypt();
            decrypt.Key = this.ContextModel.Key;
            this.XML = decrypt.Decrypt(this.ContextModel.XML.Replace(" ","+"));
            //this.XML = this.ContextModel.XML;
            if (!this.ValidateSign(this.XML))
            {
                throw new IAM.Interface.Common.Abnormity.ResponseException(700);
            }
            XmlDocument document = new XmlDocument();
            document.LoadXml(this.XML);
            //if (!this.ValidateOvertime(Convert.ToDateTime(document.DocumentElement.Attributes["RequestTime"].Value)))
            //{
            //    throw new IAM.Interface.Common.Abnormity.ResponseException(710);
            //}
            if (!this.ValidateGuid(document.DocumentElement.Attributes["TransactionID"].Value))
            {
                throw new IAM.Interface.Common.Abnormity.ResponseException(800);
            }
            IAM.Interface.Common.XMLResolution.Request request = new IAM.Interface.Common.XMLResolution.Request();
            request.XmlDocument = new XmlDocument();
            request.XmlInfo = this.XML;
            request.XmlDocument.LoadXml(request.XmlInfo);
            this.Request = request;
            XmlObjConversion conversion = new XmlObjConversion(request.GetActionType(), request.XmlDocument.DocumentElement.Name);
            conversion.CurrentXmlNode = request.GetCurrentNode();
            return conversion.ConvertToObj();
        }

        private string Send(IConvertXml obj, IAM.Interface.Common.XMLResolution.Request request, IAM.Interface.Common.Abnormity.ResponseException exception)
        {
            string plainText = "";
            plainText = new XmlObjConversion(obj).GetXml();
            AbstractXMLResolution resolution = new Response(request.GetActionType(), exception, request.GetTransactionID());
            resolution.XmlInfo = plainText;
            plainText = resolution.GetWholeXML();
            EncryptDecrypt decrypt = new EncryptDecrypt();
            decrypt.Key = this.ContextModel.Key;
            return decrypt.Encrypt(plainText);
            //return plainText;
        }

        private object TransferBLL(object obj, IAM.Interface.Common.XMLResolution.Request request)
        {
            object obj2 = null;
            IdentityMgnt mgnt = null;
            ACIMgnt mgnt2 = null;
            DelegationMgnt mgnt3 = null;
            try
            {
                this.ResponseException = new IAM.Interface.Common.Abnormity.ResponseException();
                switch (request.GetActionType())
                {
                    case ActionType.IDEN_MANAGE:
                        mgnt = new IdentityMgnt();
                        switch (request.GetOperationType())
                        {
                            case OperationType.Create:
                                return mgnt.CreateIdentity((Identity) obj);

                            case OperationType.Enable:
                                return mgnt.EnableIdentity((Identity) obj);

                            case OperationType.Disable:
                                return mgnt.DisableIdentity((Identity) obj);

                            case OperationType.Delete:
                                return mgnt.DeleteIdentity((Identity) obj);

                            case OperationType.Update:
                                return mgnt.UpdateIdentity((Identity) obj);
                        }
                        return obj2;

                    case ActionType.IDEN_GETACMODEL:
                        mgnt2 = new ACIMgnt();
                        return mgnt2.GetACIModel();

                    case ActionType.IDEN_GETUSERACI:
                        mgnt2 = new ACIMgnt();
                        return mgnt2.GetUserACI((AccountInfo) obj);

                    case ActionType.IDEN_SETUSERACI:
                        mgnt2 = new ACIMgnt();
                        var setRole = mgnt2.SetUserACI((ACI)obj);
                        if (setRole != null)
                            return setRole;
                        else
                            throw new Exception("Set User Role Failed!");

                    case ActionType.ORG_UPDATE:
                        obj2 = new OrganizationMgnt().UpdateOrganize((OrganizeInfo) obj);
                        if ((bool) obj2)
                        {
                            return new NullityObj();
                        }
                        return new NullityObj();

                    case ActionType.ORG_CREATE:
                        obj2 = new OrganizationMgnt().CreateOrganize((OrganizeInfo) obj);
                        if ((bool) obj2)
                        {
                            return new NullityObj();
                        }
                        return new NullityObj();

                    case ActionType.ORG_DELETE:
                        obj2 = new OrganizationMgnt().DeleteOrganize((OrganizeDeleteParameter) obj);
                        if ((bool) obj2)
                        {
                            break;
                        }
                        return new NullityObj();

                    case ActionType.DM_GETMODULELIST:
                        mgnt3 = new DelegationMgnt();
                        return mgnt3.GetModuleList();
                        

                    case ActionType.DM_GETDELEINFO:
                        mgnt3 = new DelegationMgnt();
                        return mgnt3.GetDelegationInfo((AccountInfo) obj);

                    case ActionType.DM_SETDELEINFO:
                        mgnt3 = new DelegationMgnt();
                        var dm_model = mgnt3.SetDelegationInfo((AIDelegations)obj);
                        if (dm_model != null)
                            return dm_model;
                        else
                            throw new Exception("Set Delegation Failed!");

                    default:
                        return obj2;
                }
                obj2 = new NullityObj();
            }
            catch (IAM.Interface.Common.Abnormity.ResponseException exception)
            {
                this.ResponseException = exception;
                return new NullityObj();
            }
            catch (Exception exception2)
            {
                this.ResponseException.SetStateMessage(500, exception2.Message);
                return new NullityObj();
            }
            return obj2;
        }

        private bool ValidateGuid(string requestguid)
        {
            return true;
        }

        private bool ValidateOvertime(DateTime requesttime)
        {
            if (Math.Abs(DateTime.Now.Subtract(requesttime).TotalMinutes) > 5.0)
            {
                return false;
            }
            return true;
        }

        public bool ValidateRequestIP(string RequestIPs)
        {
            string str = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
            //string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            //if (!(baseDirectory.Substring(baseDirectory.Length - 1) == "/") && !(baseDirectory.Substring(baseDirectory.Length - 1) == @"\"))
            //{
            //    baseDirectory = baseDirectory + @"\";
            //}
            //string filename = baseDirectory + "RequestIPs.xml";
            //XmlDocument document = new XmlDocument();
            //document.Load(filename);
            //XmlNodeList list = document.SelectNodes("//RequestIP");
            foreach (var node in RequestIPs.Split(';'))
            {
                if (node.ToLower().Trim() == str.ToLower().Trim())
                {
                    return true;
                }
            }
            return false;
        }

        public bool ValidateSign(string xml)
        {
            return true;
        }

        public ResponseContextModel ContextModel
        {
            get
            {
                return this._contextmodel;
            }
            set
            {
                this._contextmodel = value;
            }
        }

        public IAM.Interface.Common.XMLResolution.Request Request
        {
            get
            {
                return this._request;
            }
            set
            {
                this._request = value;
            }
        }

        public IAM.Interface.Common.Abnormity.ResponseException ResponseException
        {
            get
            {
                return this._re;
            }
            set
            {
                this._re = value;
            }
        }

        public string XML
        {
            get
            {
                return this._xml;
            }
            set
            {
                this._xml = value;
            }
        }
    }
}

